<template>
  <div class="forum-container">
    <!-- 顶部导航栏 -->
    <VanNavBar
      title="论坛"
      class="forum-header"
      :border="false"
    />

    <!-- 排序选项 -->
    <div class="sort-options">
      <div class="sort-btn" @click="sortByTime">
        <VanIcon name="time" class="sort-icon" />
        <span>按发布时间排序</span>
        <VanIcon :name="sortOrder === 'asc' ? 'arrow-up' : 'arrow-down'" class="sort-arrow" />
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <!-- 下拉刷新 -->
      <VanPullRefresh
        v-model="refreshing"
        @refresh="onRefresh"
        class="pull-refresh-container"
      >
        <!-- 帖子列表 -->
        <VanCellGroup class="post-list" :border="false">
          <!-- 帖子卡片 -->
          <VanCell
            v-for="(post, index) in postList"
            :key="post.postId"
            class="post-card"
            :border="false"
            @click="handlePostClick(post.postId)"
          >
            <!-- 用户信息 -->
            <div class="user-info">
              <VanImage
                :src="post.user.avatar"
                alt="用户头像"
                class="avatar"
                round
                fit="cover"
              />
              <div class="user-details">
                <span class="username">{{ post.user.username }}</span>
                <span class="post-time">{{ formatDate(post.createdAt) }}</span>
              </div>
            </div>

            <!-- 帖子内容 -->
            <div class="post-content">
              <h3 class="post-title">{{ post.title }}</h3>
              <p class="post-text">{{ post.content }}</p>
              
              <!-- 帖子封面图 -->
              <VanImage
                v-if="post.coverImage"
                :src="post.coverImage"
                alt="帖子封面"
                class="post-image"
              />
            </div>

            <!-- 帖子互动数据 -->
            <div class="post-stats">
              <div class="stat-item" @click.stop="handleLike(post.postId, index)">
                <VanIcon :name="isLiked(post.postId) ? 'like' : 'like-o'" class="stat-icon" :color="isLiked(post.postId) ? '#ff4757' : ''" />
                <span>{{ post.likes }}</span>
              </div>
              <div class="stat-item">
                <VanIcon name="comment-o" class="stat-icon" />
                <span>{{ post.comments }}</span>
              </div>
              <div class="stat-item">
                <VanIcon name="star-o" class="stat-icon" />
                <span>{{ post.collects }}</span>
              </div>
            </div>
          </VanCell>
        </VanCellGroup>
      </VanPullRefresh>
    </div>

    <!-- 右下角发布按钮 -->
    <div class="publish-float-btn" @click="showPublishDialog">
      <VanIcon name="plus" size="24" color="white" />
    </div>
      <tabbar/>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router'; // 引入路由钩子
import axios from '../utils/axios.js';
import { showToast } from 'vant';
import tabbar from '@/components/tab-bar.vue'
const router = useRouter(); // 创建路由实例

// 帖子列表数据
const postList = ref([]);
// 下拉刷新状态
const refreshing = ref(false);
// 已点赞的帖子ID集合
const likedPosts = ref(new Set());
// 排序顺序：'asc' 升序（旧到新），'desc' 降序（新到旧）
const sortOrder = ref('desc');

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const now = new Date();
  const diffTime = now - date;
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays === 0) {
    return '今天';
  } else if (diffDays === 1) {
    return '昨天';
  } else if (diffDays < 7) {
    return `${diffDays}天前`;
  } else {
    return date.toLocaleDateString('zh-CN');
  }
};

// 按时间排序
const sortByTime = () => {
  // 切换排序顺序
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  
  // 执行排序
  postList.value.sort((a, b) => {
    const dateA = new Date(a.createdAt).getTime();
    const dateB = new Date(b.createdAt).getTime();
    return sortOrder.value === 'asc' ? dateA - dateB : dateB - dateA;
  });
};

// 加载帖子数据
const loadPosts = async () => {
  try {
    const res = await axios.get('api/forumList');
    if (res.code === 200) {
      postList.value = res.data;
      // 加载完成后默认按时间降序排序（最新的在前）
      sortByTime();
    }
  } catch (error) {
    console.error('加载论坛帖子失败:', error);
  }
};

// 下拉刷新处理
const onRefresh = async () => {
  // 模拟网络请求延迟
  await new Promise(resolve => setTimeout(resolve, 1000));
  await loadPosts();
  refreshing.value = false;
};

// 处理帖子点击 - 跳转到详情页并传递ID
const handlePostClick = (postId) => {
  router.push({ path: '/forumDetail', query: { id: postId } });
};

// 处理点赞/取消点赞功能
const handleLike = async (postId, index) => {
  // 获取当前用户ID（实际应用中应该从用户登录信息中获取）
  const user = JSON.parse(sessionStorage.getItem("user"));
  const userId = user.userId;

  // 从帖子对象中获取作者ID
  const authorId = postList.value[index].user.userId;
  
  try {
    if (likedPosts.value.has(postId)) {
      // 已点赞，执行取消点赞操作
      const res = await axios.get(`/api/forumLikesDel?postId=${postId}&userId=${userId}`);
      if (res.code === 200) {
        // 取消点赞成功
        postList.value[index].likes--;
        likedPosts.value.delete(postId);
        showToast('取消点赞成功');
      } else {
        showToast(res.msg || '取消点赞失败');
      }
    } else {
      // 未点赞，执行点赞操作
      const res = await axios.post('/api/forumLikesAdd', {
        postId: postId,
        authorId: authorId, // 添加作者ID参数
        userId: userId
      });
      
      if (res.code === 200) {
        // 点赞成功
        postList.value[index].likes++;
        likedPosts.value.add(postId);
        showToast('点赞成功');
      } else {
        showToast(res.msg || '点赞失败');
      }
    }
  } catch (error) {
    console.error('操作失败:', error);
    showToast('网络错误，操作失败');
  }
};

// 检查帖子是否已被点赞
const isLiked = (postId) => {
  return likedPosts.value.has(postId);
};

// 显示发布界面 - 跳转到forumAdd组件
const showPublishDialog = () => {
  router.push('/forumAdd'); // 跳转到发布页面
};

// 组件挂载时加载数据
onMounted(() => {
  loadPosts();
});
</script>

<style lang="less" scoped>
.forum-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative; // 添加相对定位，使浮动按钮的绝对定位基于此容器
}

.forum-header {
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  
  :deep(.van-nav-bar__title) {
    font-weight: 500;
  }
}

// 排序选项样式
.sort-options {
  background-color: white;
  padding: 12px 16px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.sort-btn {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #f8f8f8;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: #f0f0f0;
  }
  
  .sort-icon {
    font-size: 16px;
    margin-right: 8px;
    color: #666;
  }
  
  span {
    font-size: 14px;
    color: #333;
  }
  
  .sort-arrow {
    font-size: 12px;
    margin-left: 8px;
    color: #999;
  }
}

.content-wrapper {
  padding-bottom: 80px; // 为底部导航栏留出空间
}

.pull-refresh-container {
  height: 100%;
}

.post-list {
  padding: 0;
}

.post-card {
  margin: 0 16px 16px;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
  }
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  
  .avatar {
    width: 36px;
    height: 36px;
    margin-right: 12px;
  }
  
  .user-details {
    display: flex;
    flex-direction: column;
    
    .username {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
    
    .post-time {
      font-size: 12px;
      color: #999;
      margin-top: 2px;
    }
  }
}

// 在.post-content中增强图片和互动数据之间的分隔
.post-content {
  padding: 16px;
  // 确保内容区域有足够的空间
  margin-bottom: 8px;
}

// 增强.post-image样式，增加底部外边距
.post-image {
  width: 100%;
  height: auto;
  max-height: 350px;
  margin-bottom: 20px; // 增加底部间距，将图片与下方互动数据分隔开
  border-radius: 8px;
  display: block;
  object-fit: contain;
}

// 增强.post-stats样式，使其更加突出和分隔
.post-stats {
  display: flex;
  justify-content: space-around;
  padding: 16px 12px;
  margin-top: 8px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
  border-radius: 8px;
  
  .stat-item {
    display: flex;
    align-items: center;
    color: #666;
    cursor: pointer;
    transition: all 0.2s;
    padding: 4px 8px;
    border-radius: 4px;
    
    &:hover {
      color: #ff4757;
      background-color: #fff5f5;
    }
    
    .stat-icon {
      font-size: 18px;
      margin-right: 6px;
      transition: color 0.2s;
    }
    
    span {
      font-size: 14px;
    }
  }
}

.publish-float-btn {
  position: fixed;
  right: 24px;
  bottom: 96px;
  width: 56px;
  height: 56px;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(255, 71, 87, 0.4);
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  z-index: 10;
  
  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 16px rgba(255, 71, 87, 0.5);
  }
}
</style>